package com.atguigu.distributed.lock.zookeeper;

import com.atguigu.distributed.lock.zookeeper.lock.ZkDistributedLock;
import org.apache.zookeeper.*;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.CountDownLatch;

/**
 * @author linjy on 2022/10/19
 */
@Component
public class ZkClient {

    private static final String connectString = "Hadoop102:2181";//Hadoop102:2181,172.16.116.100:2181

    private ZooKeeper zooKeeper;

    public ZkDistributedLock getZkDistributedLock(String lockName) {
        return new ZkDistributedLock(zooKeeper, lockName);
    }

    //项目启动的时候执行该方法
    @PostConstruct
    public void init() {
        try {
            CountDownLatch countDownLatch = new CountDownLatch(1);

            zooKeeper = new ZooKeeper(connectString, 30000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    //是否获取链接,节点发生变化也会走这里,要加多个类型判断
                    if (Event.KeeperState.SyncConnected.equals(event.getState())
                            && Event.EventType.None.equals(event.getType())) {
                        System.out.println("获取链接成功。。。。。。" + event);
                        countDownLatch.countDown();
                        //zookeeper版本不同，此处有些不一样
                    /*} else if (Event.KeeperState.Closed.equals(event.getState())) {
                        System.out.println("关闭链接。。。。。。" + event);*/
                    } else {
                        System.out.println("节点事件。。。。。。");
                    }
                }
            });

            countDownLatch.await();
        } catch (Exception e) {
            System.out.println("获取链接失败！");
            e.printStackTrace();
        }
    }

    //PreDestroy（）方法在destroy()方法执行执行之后执行
    @PreDestroy
    public void destroy() {
        try {
            if (zooKeeper != null) {
                zooKeeper.close();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
